package controller;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Date;
import java.text.ParseException;
import java.util.Iterator;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import po.Room;
import po.Student;
import po.User;
import service.ContactsService;
import userDao.UserDao;
import userDao.UserImpl.UserImpl;
import view.Dialog;
import view.Frame;
import view.LoginPanel;

public class Controller implements ActionListener, TreeSelectionListener {
	private LoginPanel loginPanel;
	private Frame win;// 这里new了Frame
	private ContactsService contactsService;
	private Dialog dialog;
	private Room room;
//	private String year, month, day;

	public Controller() {
		contactsService = new ContactsService();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		int password = 0;
		// 登录事件
		if ("login".equals(e.getActionCommand())) {
			String u1 = loginPanel.getUser().getText();
			int p1 = Integer.parseInt(loginPanel.getPassword().getText());
			UserDao dao = new UserImpl();
			password = dao.getUserPassword(u1);
			if (p1 == password) {
				win = new Frame(loginPanel);
				win.setTitle("通讯录");
				win.setController(loginPanel.getController());
			} else {
				JOptionPane.showMessageDialog(loginPanel, "您输入的用户名或密码错误,请重新登录","输入错误",JOptionPane.ERROR_MESSAGE);
			}
		}
		// 注册事件
		else if ("register".equals(e.getActionCommand())) {
				String u1 = loginPanel.getUser().getText();
				int p1 = Integer.parseInt(loginPanel.getPassword().getText());
				User user1 = new User(u1, p1);
				UserDao dao = new UserImpl();
				dao.save(user1);
				JOptionPane.showMessageDialog(loginPanel, "注册成功");
		}
		// 添加对话框
		else if ("add".equals(e.getActionCommand())) {
			dialog = new Dialog(loginPanel, "添加", null);
		}
		// 添加事件
		else if ("addButton".equals(e.getActionCommand())) {
			Student newStudent = this.getInput();
			if (newStudent != null) {
				contactsService.save(newStudent);
				JOptionPane.showMessageDialog(win, "添加" + newStudent.getStudentName() + "信息成功");
				dialog.dispose();// 释放上面的信息对话框
				win.refresh(contactsService.findAll());
				win.refreshTree(contactsService.findAllRoom());
			} else {
				JOptionPane.showMessageDialog(win, "添加失败");
			}
		}
		// 删除学生事件
		else if ("delete".equals(e.getActionCommand())) {
			String str = JOptionPane.showInputDialog(win, "请输入学号");// 输入对话框
			if (str != null && !"".equals(str)) { // str不为null且str内容不为""
				String studentId = contactsService.getId(str);
				if (studentId != null) {
					contactsService.delete(str);
					win.refresh(contactsService.findAll());
				} else {
					JOptionPane.showMessageDialog(win, "您输入的学号有误，请重新输入", "输入错误", JOptionPane.ERROR_MESSAGE);
				}
			}

		}
		// 删除宿舍事件
		else if ("deleteRoom".equals(e.getActionCommand())) {
			String str2 = JOptionPane.showInputDialog(win, "请输入房名");
			if (str2 != null && str2 != "") {
				String roomName = contactsService.getRoomName(str2);
				if (roomName != null) {
					contactsService.roomDelete(str2);
					win.refresh(contactsService.findAll());
					win.refreshTree(contactsService.findAllRoom());
				} else {
					JOptionPane.showMessageDialog(win, "您输入的房名不存在,请重新输入", "输入错误", JOptionPane.ERROR_MESSAGE);
				}
			}
		}
		// 修改操作的输入对话框
		else if ("update".equals(e.getActionCommand())) {
			String str1 = JOptionPane.showInputDialog(win, "请输入学号");
			if (str1 != null && !"".equals(str1)) {
				String studentId = contactsService.getId(str1);
				if (studentId != null) {
					Student stu = contactsService.getReturnStudent(str1);
					dialog = new Dialog(loginPanel, "修改", stu);
				} else {
					JOptionPane.showMessageDialog(win, "您输入的学号有误，请重新输入", "输入错误", JOptionPane.ERROR_MESSAGE);
				}
			}
		}
		// 修改事件
		else if ("updateButton".equals(e.getActionCommand())) {
			Student updateStudent = this.getInput();
			if (updateStudent != null) {
				contactsService.update(updateStudent);
				contactsService.roomUpdate(updateStudent.getRoom());
				JOptionPane.showMessageDialog(win, "修改信息成功");
				dialog.dispose();// 释放上面的信息对话框
				win.refresh(contactsService.findAll());
				win.refreshTree(contactsService.findAllRoom());
			} else {
				JOptionPane.showMessageDialog(win, "修改失败");
			}
		}
		// 姓名查询事件
		else if ("findByStudentId".equals(e.getActionCommand())) {
			String str = JOptionPane.showInputDialog(win, "请输入学号");// 输入对话框
			if (str != null && !"".equals(str)) {
				List<Student> result = contactsService.get(str);
				win.showSearchResult(result);
			}
		} else if ("findAll".equals(e.getActionCommand())) {
			List<Student> allStudent = contactsService.findAll();
			win.findAll(allStudent);
		}
	}

	/**
	 * @return 获取输入内容
	 * @throws ParseException
	 */
	private Student getInput() {
		String studentId = null;
		String studentName = null;
		Date studentBirthday = null;
		String studenttelephoneNo = null;
		String studentAddress = null;
		String studentEmail = null;
		String roomName;
		int roomNo;
		Student stu = null;
		// 学号输入框
		String studentIdInput = dialog.getStudentIdTextField().getText().trim();
		if (studentIdInput != null && !"".equals(studentIdInput)) {
			studentId = studentIdInput;
		} else {
			JOptionPane.showMessageDialog(win, "学号不能为空", "输入错误", JOptionPane.ERROR_MESSAGE);
		}
		// 姓名输入框
		String studentNameInput = dialog.getNameTextField().getText().trim();
		if (studentNameInput != null && !"".equals(studentNameInput)) {
			studentName = studentNameInput;
		} else {
			JOptionPane.showMessageDialog(win, "姓名不能为空", "输入错误", JOptionPane.ERROR_MESSAGE);
		}
		// 生日输入框
		// 判断生日输入格式是否符合格式的正则表达式
		java.sql.Date d2;// 将string型数据转成date型
		String studentBirthdayInput = dialog.getBirthdatTextField().getText().trim();
		if (studentBirthdayInput != null && studentBirthdayInput.matches("^\\d{4}-\\d{2}-\\d{2}$")) {
			d2 = java.sql.Date.valueOf(studentBirthdayInput);// 将string型数据转成date型
			studentBirthday = d2;
		} else {
//			JOptionPane.showMessageDialog(win, "生日不能为空", "输入错误", JOptionPane.ERROR_MESSAGE);			
			JOptionPane.showMessageDialog(win, "请按“xxxx-xx-xx”的格式输入生日", "输入错误", JOptionPane.ERROR_MESSAGE);
		}
		// 生日下拉框
//		int month1 = Integer.parseInt(month);
//		int day1 = Integer.parseInt(day);
//		if(month1>9&&day1<10) {
//			birthday = year+"-"+month+"-0"+day;
//		}
//		else if(month1<10&&day1>9) {
//			birthday = year+"-0"+month+"-"+day;
//		}
//		else if(month1<10&&day1<10){
//			birthday = year+"-0"+month+"-0"+day;
//		}
//		else {
//			birthday = year+"-"+month+"-"+day;
//		}
//		java.sql.Date d3;// 将string型数据转成date型
//		d3 = java.sql.Date.valueOf(birthday);// 将string型数据转成date型
//		studentBirthday = d3;

		// 电话输入框
		String studenttelephoneNoInput = dialog.getPhoneNumberTextField().getText().trim();
		if (studenttelephoneNoInput != null && !"".equals(studenttelephoneNoInput)) {
			studenttelephoneNo = studenttelephoneNoInput;
		} else {
			JOptionPane.showMessageDialog(win, "电话不能为空", "输入错误", JOptionPane.ERROR_MESSAGE);
		}
		// 地址输入框
		String studentAddressInput = dialog.getAddressTextField().getText().trim();
		if (studentAddressInput != null && !"".equals(studentAddressInput)) {
			studentAddress = studentAddressInput;
		} else {
			JOptionPane.showMessageDialog(win, "地址不能为空", "输入错误", JOptionPane.ERROR_MESSAGE);
		}
		// 邮箱输入框
		String studentEmailInput = dialog.getEmailTextField().getText().trim();
		if (studentEmailInput != null && !"".equals(studentEmailInput)) {
			studentEmail = studentEmailInput;
		} else {
			JOptionPane.showMessageDialog(win, "邮箱不能为空", "输入错误", JOptionPane.ERROR_MESSAGE);
		}
		// 房名输入框
		String roomNameInput = dialog.getRoomNameTextField().getText().trim();
		if (roomNameInput != null && !"".equals(roomNameInput)) {
			roomName = roomNameInput;// 拿到的是"xxx室"
//	        String str = roomName.replaceAll("[^\\d]+", "");//去掉非数字字符
//	        roomNo = Integer.parseInt(str);
//			room = new Room(roomNo, roomName);//但这里new room 其实不是数据库的那个Room对象 而是一个新的room
			room = contactsService.getRoom(roomName);
			if (room == null) {
				String str = roomName.replaceAll("[^\\d]+", "");// 去掉非数字字符
				roomNo = Integer.parseInt(str);
				room = new Room(roomNo, roomName);
				contactsService.roomSave(room);
			}
		} else {
			JOptionPane.showMessageDialog(win, "请按“xxx室”的格式输入房名", "输入错误", JOptionPane.ERROR_MESSAGE);
		}
		if (studentId != null && studentName != null && studentBirthday != null && studenttelephoneNo != null
				&& studentAddress != null && studentEmail != null && room != null) {
			stu = new Student(studentId, studentName, studentBirthday, studenttelephoneNo, studentAddress, studentEmail,
					room);
		} else {
			JOptionPane.showMessageDialog(win, "有数据未输入或输入格式有误", "输入错误", JOptionPane.ERROR_MESSAGE);
		}
		return stu;
	}

	public void setLoginPanel(LoginPanel loginPanel) {
		this.loginPanel = loginPanel;
	}

	/**
	 *
	 *树组件的点击事件 即查找此宿舍的学生信息
	 */
	public void valueChanged(TreeSelectionEvent e) {
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) win.getTree().getLastSelectedPathComponent();
		Iterator<Room> iter = win.getRoomNameList().iterator();
		List<Student> result = null;
		for (int i = 0; i < win.getRoomNameList().size(); i++) {
			while (iter.hasNext()) {
				Room r = iter.next();
				if (node.toString().equals(r.getRoomName())) {// node.toString()获取节点名
					result = contactsService.findByRoom(r.getRoomName());
					win.showSearchResult(result);
				}
			}
		}
	}

//	@Override
//	public void itemStateChanged(ItemEvent e) {
//		year = dialog.getYearDate().getSelectedItem().toString();
//		month = dialog.getMonthDate().getSelectedItem().toString();
//		day = dialog.getDayDate().getSelectedItem().toString();
//	}

	public Frame getFrame() {
		return win;
	}

	public void setFrame(Frame frame) {
		this.win = frame;
	}

	public void setContactsService(ContactsService contactsService) {
		this.contactsService = contactsService;
	}

	public ContactsService getContactsService() {
		return contactsService;
	}

	public void setStudentAddDialog(Dialog studentAddDialog) {
		this.dialog = studentAddDialog;
	}

	public Room getRoom() {
		return room;
	}

	public void setRoom(Room room) {
		this.room = room;
	}

}
